package com.home.cca.network;

import android.app.Application;
import android.content.SharedPreferences;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class ApiClient extends Application {
    private static ApiClient instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    private static final String base_url = "https://sa.lystcgjg.com:8880";
    private static final OkHttpClient client = new OkHttpClient.Builder().build();

    public static String execute(Request request) throws IOException {
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求异常" + response);
            }
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                throw new IOException("请求体为空");
            }
            return responseBody.string();
        }
    }

    public static OkHttpClient getClient() {
        return client;
    }

    public static String getBaseUrl() {
        return base_url;
    }

    public static String getCookie() throws IOException {
        String dataKey = "dataKey";
        String cookieKey = "cookieKey";
        String cookieTimeKey = "cookieTimeKey";

        SharedPreferences preferences = instance.getSharedPreferences(dataKey, MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        String cookie = preferences.getString(cookieKey, "");
        long cookieTime = preferences.getLong(cookieTimeKey, 0);

        editor.putLong(cookieTimeKey, System.currentTimeMillis());

        if (System.currentTimeMillis() - cookieTime > TimeUnit.MINUTES.toMillis(10)) {
            String login = LoginRequest.login();
            editor.putString(cookieKey, login);
            editor.apply();
            return login;
        }
        return cookie;
    }
}